package main

import (
	"deepseek-chat/internal/config"
	"deepseek-chat/internal/db"
	"deepseek-chat/internal/handlers"
	"deepseek-chat/internal/ws"
	"log"
	"net/http"
)

func main() {
	// Load configuration
	cfg := config.Load()

	// Initialize Database
	if err := db.Init(cfg); err != nil {
		log.Fatalf("failed to init db: %v", err)
	}
	if err := db.SeedDefaultTopicIfEmpty(); err != nil {
		log.Fatalf("failed to seed default topic: %v", err)
	}

	// Load persisted API key
	if key, err := db.LoadDecryptedAPIKey(); err == nil && key != "" {
		config.GlobalKeyStore.Set(key)
		log.Println("Loaded persisted API key from database")
	} else if err != nil {
		log.Printf("Failed to load persisted API key: %v", err)
	}

	// Initialize WebSocket Hub
	hub := ws.NewHub()
	go hub.Run()

	// Initialize Handlers
	h := handlers.New(hub)

	// Static file server
	fs := http.FileServer(http.Dir("static"))
	http.Handle("/", fs)

	// WebSocket endpoint
	http.HandleFunc("/ws", hub.HandleWS)

	// API Endpoints
	http.HandleFunc("/api/config/key", h.HandleConfigKey)
	http.HandleFunc("/api/topics", h.HandleTopics)
	http.HandleFunc("/api/topics/", h.HandleDeleteTopic)
	http.HandleFunc("/api/messages", h.HandleGetMessages)
	http.HandleFunc("/api/messages/create", h.HandleCreateMessage)
	http.HandleFunc("/api/messages/", h.HandleDeleteMessage)
	http.HandleFunc("/api/status", h.HandleStatus)
	http.HandleFunc("/api/processes", h.HandleProcesses)
	http.HandleFunc("/api/chat", h.HandleChat)
	http.HandleFunc("/api/balance", h.HandleBalance)

	log.Printf("Server listening on :%s", cfg.Port)
	log.Fatal(http.ListenAndServe(":"+cfg.Port, nil))
}
